package se.hrbustrc.hlgshopping.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import se.hrbustrc.hlgshopping.dto.LoginRequest;
import se.hrbustrc.hlgshopping.dto.LoginResponse;
import se.hrbustrc.hlgshopping.entity.User;
import se.hrbustrc.hlgshopping.service.UserService;
import se.hrbustrc.hlgshopping.utils.JwtUtils;
import se.hrbustrc.hlgshopping.utils.Result;

//登录相关Controller
@RestController
@Tag(name = "用户登录接口", description = "用户登录接口")
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    UserService userService;
    @Autowired
    JwtUtils jwtUtils;
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest){
        try{
            LoginResponse loginResponse = userService.login(loginRequest);
            return new Result().ok(loginResponse);
        } catch (Exception e){
            Result result = new Result();
            result.setCode(400);
            result.setMsg("登录失败");
            result.setData(e.getMessage());
            return result;
        }
    }
    //获取用户信息
    @PostMapping("/userInfo")
    public Result getUserInfo(@RequestHeader("Authorization") String token){
        if(token!=null && token.startsWith("Bearer ")){
            token = token.substring(7);
        }
        String userCode = jwtUtils.getUsernameFromToken(token);
        System.out.println("userCode: " + userCode);
        Long userId = jwtUtils.getUserIdFromToken(token);
        System.out.println("userId: " + userId);
        User user = userService.getUserByCode(userCode);
        return new Result().ok(user);
    }
    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        try{
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setUserPass(encoder.encode(user.getUserPass()));
            userService.addUser(user);
            return new Result().ok("注册成功");
        } catch (Exception e){
            Result result = new Result();
            result.setCode(400);
            result.setMsg("注册失败");
            result.setData(e.getMessage());
            return result;
        }
    }

}
